package com.v9.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.v9.common.core.service.DefaultService;
import com.v9.common.exception.BizException;
import com.v9.system.domain.ApplicationRelease;
import com.v9.system.mapper.ApplicationReleaseMapper;
import com.v9.system.service.ApplicationReleaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApplicationReleaseServiceImpl extends DefaultService<ApplicationReleaseMapper, ApplicationRelease> implements ApplicationReleaseService {

    @Override
    public void upload(String url, Long applicationId, String versionNumber, String content, Boolean forceUpdate) {
        ApplicationRelease release = new ApplicationRelease();
        release.setApplicationId(applicationId);
        release.setVersionNumber(versionNumber);
        release.setUpdateContent(content);
        release.setForceUpdate(forceUpdate);
        release.setDownloadLink(url);
        release.setCurrentVersion(false);
        insert(release);
    }

    @Override
    @Transactional
    public void setCurrent(Long id) {
        ApplicationRelease release = findById(id);
        if (null == release) {
            throw new BizException("版本错误");
        }
        Long applicationId = release.getApplicationId();
        UpdateWrapper<ApplicationRelease> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", applicationId);
        updateWrapper.eq("currentVersion", 1);
        updateWrapper.set("currentVersion", 0);
        updateWrapper.set("update_time", new Date());

        update(updateWrapper);

        ApplicationRelease updateRelease = new ApplicationRelease();
        updateRelease.setId(id);
        updateRelease.setCurrentVersion(true);
        save(updateRelease);
    }


    public void remove(Long id) {
        ApplicationRelease release = findById(id);
        if (null == release) {
            throw new BizException("版本错误");
        }

        if (release.getCurrentVersion()) {
            throw new BizException("此版本为当前版本，不可删除");
        }
        super.remove(id);
    }
}
